/*
    yandexnarodManage

    Copyright (c) 2008 by Alexander Kazarin <boiler@co.ru>

 ***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************
*/

#include "yandexnarodmanage.h"
#include "requestauthdialog.h"


yandexnarodManage::yandexnarodManage(QString m_profile_name)
{
	setupUi(this);
	frameProgress->hide();
	frameFileActions->hide();

	QSettings settings(QSettings::IniFormat, QSettings::UserScope, "qutim/qutim."+m_profile_name, "plugin_yandexnarod");
	narodLogin = settings.value("auth/login").toString();
	narodPasswd = settings.value("auth/passwd").toString();

	netman = new QNetworkAccessManager();
	connect ( netman, SIGNAL ( finished( QNetworkReply* ) ), this, SLOT ( netrpFinished( QNetworkReply* ) ) );

	listWidget->clear();
	
	QPixmap iconimage(":/icons/yandexnarod-icons-files.png");
	for (int i=0; i<(iconimage.width()/16); i++) {
		QIcon icon(iconimage.copy((i*16),0,16,16));
		fileicons.append(icon);
	}

	fileiconstyles["b-icon-music"] = 0;
	fileiconstyles["b-icon-video"] = 1;
	fileiconstyles["b-icon-arc"] = 2;
	fileiconstyles["b-icon-doc"] = 3;
	fileiconstyles["b-icon-soft"] = 4;
	fileiconstyles["b-icon-unknown"] = 5;
	fileiconstyles["b-icon-picture"] = 14;

}

void yandexnarodManage::on_btnReload_clicked()
{
	action = "get_filelist";
	filesnum=0;
	fids.clear();
	listWidget->clear();
	btnReload->hide();
	progressBar->setMaximum(1);
	progressBar->setValue(0);
	frameProgress->show();
	netmanDo();
}

void yandexnarodManage::netmanDo() {
	for (int i=0; i<cooks.size(); ++i) netreq.setRawHeader("Cookie", cooks[i].toLatin1());
	if (cooks.isEmpty() && netreq.url().toString() != "http://passport.yandex.ru/passport?mode=auth") {
		labelStatus->setText("Authorizing...");
		if (narodLogin.isEmpty() || narodPasswd.isEmpty()) {
			requestAuthDialog authdialog;
			authdialog.setLogin(narodLogin);
			if (authdialog.exec()) {
				narodLogin = authdialog.getLogin();
				narodPasswd = authdialog.getPasswd();
			}
		}
		netreq.setUrl(QUrl("http://passport.yandex.ru/passport?mode=auth"));
		netman->post(netreq, "login=" + narodLogin.toLatin1() + "&passwd=" + narodPasswd.toLatin1());
	}
	else if (!filesnum) {
		netreq.setUrl(QUrl("http://narod.yandex.ru"));
		netman->get(netreq);
	}
	else {
		for (int i=0; i<cooks.size(); ++i) netreq.setRawHeader("Cookie", cooks[i].toLatin1());
		if (action=="get_filelist") {
			netreq.setUrl(QUrl("http://narod.yandex.ru/disk/all/page1/?sort=cdate%20desc"));
			netman->get(netreq);
		}
	}
}

void yandexnarodManage::netrpFinished( QNetworkReply* reply ) {
	if (reply->url().toString()=="http://passport.yandex.ru/passport?mode=auth") {
		bool auth_ok=false;
		QString cookstr = reply->rawHeader("Set-Cookie");
		QStringList cooklist = cookstr.split(", ");
		for (int i=0; i<cooklist.size(); ++i) {
			QStringList cookargs = cooklist[i].split("; ");
			cooks.append(cookargs[0]);
			QStringList cookval = cookargs[0].split("=");
			if (cookval[0]=="yandex_login" && !cookval[1].isEmpty()) {
				auth_ok=true;
			}
		}
		if (auth_ok) netmanDo();
		else {
			cooks.clear();
			labelStatus->setText("Authorizing failed");
		}
	}
	else {
		page = reply->readAll();
		if (!filesnum && reply->url().toString()=="http://narod.yandex.ru") {
			QRegExp rx("<p\\sclass=\"stat\">(\\d+)");
			if (rx.indexIn(page)>0) {
				filesnum = rx.capturedTexts()[1].toInt();
				progressBar->setMaximum(filesnum);
				netmanDo();
			}
		}
		if (action == "get_filelist") {
			labelStatus->setText("Downloading filelist...");
			int cpos=0;
			QRegExp rx("class=\"b-icon\\s(\\S+)\"[^<]+<img[^<]+</i[^<]+</td[^<]+<td[^<]+<input[^v]+value=\"(\\d+)\"[^<]+</td[^<]+<td[^<]+<span\\sclass='b-fname'><a\\shref=\"(\\S+)\">([^<]+)");
			cpos = rx.indexIn(page);
			while (cpos>0) {
				QString filename = rx.capturedTexts()[4];
				listWidget->addItem(QString::fromUtf8(filename.toLatin1()));
				QString iconstyle = rx.capturedTexts()[1];
				int iconint = fileiconstyles[iconstyle];
				listWidget->item(listWidget->count()-1)->setIcon(fileicons[iconint]);
				fids.append(rx.capturedTexts()[2]);
				furls.append(rx.capturedTexts()[3]);
				progressBar->setValue(fids.count());
				cpos = rx.indexIn(page, cpos+1);
			}
			QRegExp rxnp("<a\\sid=\"next_page\"\\shref=\"([^\"]+)\"");
			cpos = rxnp.indexIn(page);
			if (cpos>0 && rxnp.capturedTexts()[1].length()) {
				netreq.setUrl(QUrl("http://narod.yandex.ru"+rxnp.capturedTexts()[1]));
				netman->get(netreq);
			}
			else {
				labelStatus->setText("Filelist downloaded ("+QString::number(filesnum)+" files)");
				if (progressBar->maximum()==1 && progressBar->value()<1) progressBar->setValue(1);
			}

		}
		else if (action=="delete") {
			labelStatus->setText("File(s) deleted");
			progressBar->setValue(1);
			for (int i=0; i<listWidget->count(); i++) {
				if (listWidget->item(i)->isSelected()) {
					delete listWidget->item(i);
				}
			}
		}

	}
}

void yandexnarodManage::on_listWidget_pressed(QModelIndex)
{
	if (progressBar->value()==progressBar->maximum()) frameProgress->hide();
	if (frameFileActions->isHidden()) frameFileActions->show();
}

void yandexnarodManage::on_btnClipboard_clicked()
{
	QString text;
	for (int i=0; i<listWidget->count(); i++) {
		if (listWidget->item(i)->isSelected()) {
			text += furls[i]+"\n";
		}
	}
	QClipboard *clipboard = QApplication::clipboard();
	clipboard->setText(text);
}

void yandexnarodManage::on_btnDelete_clicked()
{
	action = "delete";
	QByteArray postData;
	postData.append("action=delete");
	for (int i=0; i<listWidget->count(); i++) {
		if (listWidget->item(i)->isSelected()) {
			listWidget->item(i)->setIcon(fileicons[15]);
			postData.append("&fid="+fids[i]);
		}
	}
	progressBar->setMaximum(1);
	progressBar->setValue(0);
	labelStatus->setText("Deleting file(s)...");
	frameProgress->show();
	frameFileActions->hide();	
	netreq.setUrl(QUrl("http://narod.yandex.ru/disk/all/"));
	netman->post(netreq, postData);
}
